package org.rmm.representation;

import java.util.Collection;

import org.rmm.model.Customer;
import org.rmm.model.Item;
import org.rmm.model.Order;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;

public class OrderRepresentation {
	
	public static String newline = System.getProperty("line.separator");

	public String asJSON(final Order order) {
		XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
		xstream.setMode(XStream.NO_REFERENCES);
		xstream.alias("order", Order.class);

		return xstream.toXML(order);
	}
	
	public String asXML(final Order order) {
		XStream xstream = new XStream();
		xstream.setMode(XStream.NO_REFERENCES);
		xstream.alias("order", Order.class);
		return xstream.toXML(order);
	}
	
	public String asXML(final Collection<Order> orders) {
		String result ="<orders>"+ newline; 
		for (Order orderElement : orders) {
			result = result + this.asXML(orderElement) + newline;
		}
		result = result + "</orders>";
		return result;
	}
	
	public void writeXMLOrderRepresentation(){
		Order order = createOrder("1");
		//XStream xstream = new XStream(new StaxDriver());
		//XStream xstream = new XStream(new DomDriver());
		XStream xstream = new XStream();
		xstream.setMode(XStream.NO_REFERENCES);
		xstream.alias("order", Order.class);
		
		System.out.println(xstream.toXML(order));		
	
	}

	private Order createOrder(String id) {
		Order order = new Order();
		order.setCurrency("USD");
		order.setCustomer(this.customerFixtureFactoryDefault());
		order.setId(id);
		order.setPlaced(true);
		order.setStatus("Placed");
		order.addItem(this.itemFixtureFactory("1", 12.34, 2));
		order.addItem(this.itemFixtureFactory("2", 213.34, 1));
		return order;
	}
	
	public Order fromXML(String xml){
		XStream xstream = new XStream();
		xstream.alias("order", Order.class);
		return (Order)xstream.fromXML(xml);
	}

	private Customer customerFixtureFactoryDefault() {
		Customer c = new Customer();
		c.setEmail("javier@test.com");
		c.setName("javier");
		return c;
	}

	private Item itemFixtureFactory(String id, Double price, Integer quantity) {
		Item i = new Item();
		i.setId(id);
		i.setPrice(price);
		i.setQuantity(quantity);
		return i;
	}

	public static void main(String[] args) {
		String xml = "<order> <id>1</id> <currency>USD</currency>  <status>Placed</status>  <placed>true</placed>  <customer>    <name>javier</name>    <email>javier@test.com</email>  </customer> </order>";
		new OrderRepresentation().writeXMLOrderRepresentation();
//		Collection<Order> orders = Repository.INSTANCE.getOrders();
//		System.out.println(new OrderRepresentation().asXML(orders));
		System.out.println(new OrderRepresentation().fromXML(xml).toString());
	}
}